package com.lge.remoteshot.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.util.Log;

import com.lge.remoteshot.camera.CameraActivity;

public class ClientActionThread extends Thread {
	private CameraActivity activity;

	private Socket sock;
	private InputStream is;
	private OutputStream os;

	private byte[] buffer = new byte[128];
	
	private String host;

	public ClientActionThread(CameraActivity activity, String host) {
		// TODO Auto-generated constructor stub
		this.activity = activity;
		this.host = host;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			sock = new Socket();
			sock.connect((new InetSocketAddress(host, ServerManager.SERVER_ACTION_PORT)),
					ClientManager.SOCKET_TIMEOUT);
			os = sock.getOutputStream();
			is = sock.getInputStream();
			Log.d(CameraActivity.TAG, "ClientThread:run:is,cos created");
			int read = 0;
			while ((read = is.read(buffer)) != -1) {
				String msg = new String(buffer, 0, read);
				activity.setReceivedAction(msg);
				Log.d(CameraActivity.TAG, "ClientThread:run:receiveMsg:" + msg);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:run:IOException : " + e.toString() + e.getMessage());
		} finally {
			try {
				if (is != null)
					is.close();
				if (os != null)
					os.close();
				if (sock != null)
					sock.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.d(CameraActivity.TAG, "ClientThread:run:finally:IOException : " + e.toString()
						+ e.getMessage());
			}
		}
	}

	public void sendAction(String action) {
		try {
			if (os != null) {
				os.write(action.getBytes());
				os.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:sendAction:IOException:" + e.toString() + e.getMessage());
		}
	}

	public void sendFileData(byte[] data) {
		try {
			if (os != null) {
				os.write(data);
				os.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:sendFrameData:IOException:" + e.toString() + e.getMessage());
		}
	}

	public void stopThread() {
		try {
			if (is != null)
				is.close();
			if (os != null)
				os.close();
			if (sock != null)
				sock.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"ClientThread:stopThread:IOException : " + e.toString() + e.getMessage());
		}
	}
}